<?php

//商品

class Goods extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('goods_model');
	}

	public function index()
	{
		$category_id = intval(get('category_id')); //分类id
		$category_id = $category_id > 0 ? $category_id : 0;
		$p = intval(get('p')); //页码，从1开始
		$p = $p > 0 ? $p : 1;
		$per_page = 20; //每页记录数
		
		$count = $this->goods_model->get_count_by_category($category_id); //总数
		
		$goods_list = $this->goods_model->get_page_by_category($p, $per_page, $category_id); //分页数据
		
		$this->load->library('page');
		$config = array(
			'base_url' => admin_url('goods/index', array('category_id' => $category_id)),
			'total_rows' => $count,
			'current_page' => $p,
			'per_page' => $per_page
		);
		$this->page->config($config)->init();
		
		$this->template->assign('list', $goods_list);
		$this->template->assign('page', $this->page);
		$this->template->display('goods/list');
	}

	//添加页面
	protected function _insert_get()
	{
		$this->load->model('category_model');
		$category_list = $this->category_model->get_all();
		
		$this->load->library('tree');
		$config = array(
			'list' => $category_list,
			'fid_name' => 'parent_id'
		);
		$this->tree->config($config)->init();
		$category_list = $this->tree->get();
		
		$this->load->model('brand_model');
		$brand_list = $this->brand_model->get_all();
		
		$this->template->assign('category_list', $category_list);
		$this->template->assign('brand_list', $brand_list);
		$this->template->display('goods/insert');
	}
	
	//提交添加分类
	protected function _insert_post()
	{	
		$category_id = intval(post('category_id'));
		$name = trim(post('name'));
		$title = trim(post('title'));
		$keywords = trim(post('keywords'));
		$description = trim(post('description'));
		$content = trim(post('content'));
		
		if ($name == '')
		{
			msg('名称必须填写！', -1);
		}
		elseif ($category_id < 1)
		{
			msg('分类必须指定！', -1);
		}
		
		$this->load->model('category_model');
		$category_data = $this->category_model->get($category_id);
		if ( ! $category_data)
		{
			msg('分类不存在！', -1);
		}
		
		if ($this->goods_model->exists(array('name' => $name, 'category_id' => $category_id)))
		{
			msg('名称已经存在！', -1);
		}
		
		$data = array(
			'category_id' => $category_id, //分类id
			'name' => $name, //商品名称，必须填写
			'title' => $title, //标题
			'keywords' => $keywords, //关键词
			'description' => $description, //描述
			'content' => $content //内容
		);
		
		$id = $this->goods_model->insert($data);
		if ( ! $id)
		{
			log_message('error', '添加商品失败！原因：写入goods表失败！');
			msg('添加失败！');
		}
		
		$msg = '添加成功！<br /><br /><a href="'.admin_url('goods/update', array('id' => $id)).'" class="button">返回修改</a>&nbsp;&nbsp;&nbsp;<a href="'.admin_url('goods/insert').'" class="button">继续添加</a>&nbsp;&nbsp;&nbsp;<a href="'.$this->session->get('back').'" class="button">返回列表</a>';
		msg($msg);
	}
	
	//修改页面
	protected function _update_get()
	{
		$id = intval(get('id'));
		if ($id < 1)
		{
			show_error('非法访问！');
		}
		
		$goods_data = $this->goods_model->get($id);
		if ( ! $goods_data)
		{
			msg('商品不存在！', admin_url('goods/index'));
		}
		
		$this->load->model('category_model');
		$category_list = $this->category_model->get_all();
		
		$this->load->library('tree');
		$config = array(
			'list' => $category_list,
			'fid_name' => 'parent_id'
		);
		$this->tree->config($config)->init();
		$category_list = $this->tree->get();
		
		$this->load->model('brand_model');
		$brand_list = $this->brand_model->get_all();
		
		$this->load->model('supplier_model');
		$supplier_list = $this->supplier_model->get_all();
		
		$this->load->model('picture_model');
		$picture_list = $this->picture_model->get_all(array('goods_id' => $id, 'expired' => 0), '*', 'order asc');
		
		$this->template->assign('data', $goods_data);
		$this->template->assign('category_list', $category_list);
		$this->template->assign('brand_list', $brand_list);
		$this->template->assign('supplier_list', $supplier_list);
		$this->template->assign('picture_list', $picture_list);
		$this->template->display('goods/update');
	}
	
	//提交修改信息
	protected function _update_post()
	{
		$id = intval(post('id'));
		$category_id = intval(post('category_id')); //分类id
		$brand_id = intval(post('brand_id')) ? intval(post('brand_id')) : 0; //品牌id
		$supplier_id = intval(post('supplier_id')) > 0 ? intval(post('supplier_id')) : 0; //供应商id
		$name = trim(post('name')); //商品名称
		$sku = trim(post('sku')); //货号
		$weight = intval(post('weight')) > 0 ? intval(post('weight')) : 0; //重量 单位克
		$cost_price = floatval(post('cost_price')) > 0 ? floatval(post('cost_price')) : 0; //成本价格
		$market_price = floatval(post('market_price')) > 0 ? floatval(post('market_price')) : 0; //市场价
		$sale_price = floatval(post('sale_price')) > 0 ? floatval(post('sale_price')) : 0; //销售价
		$on_sale = intval(post('on_sale')) > 0 ? 1 : 0; //上下架
		$stock = intval(post('stock')) > 0 ? intval(post('stock')) : 0; //库存
		$pic = trim(post('pic')); //图片
		$title = trim(post('title')); //标题
		$keywords = trim(post('keywords')); //关键词
		$description = trim(post('description')); //描述
		$content = trim(post('content')); //内容
		$urls = post('urls');
		
		$pictures = array();
		if ($urls)
		{
			$this->load->helper('file');
			foreach ($urls as $i => $url)
			{
				if (file_exists($_SERVER['DOCUMENT_ROOT'].ltrim($url, '/')) && in_array(get_extension($url), array('jpg', 'jpeg', 'png', 'gif')))
				{
					$pictures[] = array(
						'url' => trim($url),
						'order' => $i
					);
				}
			}
		}
		
		if ($id < 1)
		{
			show_error('非法访问！');
		}
		elseif ($category_id < 1)
		{
			msg('分类必须指定！', -1);
		}
		
		$this->load->model('category_model');
		$category_data = $this->category_model->get($category_id);
		if ( ! $category_data)
		{
			msg('分类不存在！', -1);
		}
		
		$goods_data = $this->goods_model->get($id);
		if ( ! $goods_data)
		{
			msg('商品不存在！', admin_url('goods/index'));
		}
		
		if ($goods_data['name'] != $name || $goods_data['category_id'] != $category_id)
		{
			if ($this->goods_model->exists(array('name' => $name, 'category_id' => $category_id)))
			{
				msg('此分类下的商品名称已经存在！', -1);
			}
		}
		
		$this->db->trans_start();
		
		try
		{
			$data = array(
				'category_id' => $category_id,
				'brand_id' => $brand_id,
				'supplier_id' => $supplier_id,
				'name' => $name,
				'sku' => $sku,
				'weight' => $weight,
				'cost_price' => $cost_price,
				'market_price' => $market_price,
				'sale_price' => $sale_price,
				'on_sale' => $on_sale,
				'stock' => $stock,
				'pic' => $pic,
				'title' => $title,
				'keywords' => $keywords,
				'description' => $description,
				'content' => $content
			);
			
			if (FALSE === $this->goods_model->update($data, $id))
			{
				throw new Exception('修改商品失败！原因：更新goods表失败！');
			}
			
			$this->load->model('picture_model');
			
			//让旧的过期
			if (FALSE === $this->picture_model->update(array('expired' => 1, 'expired_datetime' => date('Y-m-d H:i:s')), array('goods_id' => $id)))
			{
				throw new Exception('修改商品失败！原因：更新picture表失败！');
			}
					
			if ($pictures)
			{
				foreach ($pictures as $picture)
				{					
					if( ! $this->picture_model->insert(array('goods_id' => $id, 'url' => $picture['url'], 'order' => $picture['order'])))
					{
						throw new Exception('修改商品失败！原因：写入picture表失败！');
					}
				}
			}
			
			$this->db->trans_commit();
			
		}
		catch (Exception $e)
		{
			$this->db->trans_rollback();
			log_message('error', $e->getMessage());
			msg('修改失败！', -1);
		}
		
		$msg = '修改成功！<br /><br /><a href="'.admin_url('goods/update', array('id' => $id)).'" class="button">继续修改</a>&nbsp;&nbsp;&nbsp;<a href="'.$this->session->get('back').'" class="button">返回列表</a>';
		msg($msg);
	}
	
	//删除
	public function _delete_ajax()
	{
		$id = intval(get('id'));
		
		if ($id < 1)
		{
			ajax(array('error' => 1, 'msg' => '非法访问！'));
		}
		
		$result = $this->goods_model->delete($id);
		
		if ($result !== FALSE)
		{
			ajax(array('error' => 0, 'msg' => '删除成功！'));
		}
		elseif ($result === FALSE)
		{
			log_message('error', '删除商品失败！原因：更新goods表失败！');
			ajax(array('error' => 2, 'msg' => '删除失败！'));
		}
	}
	
	//上传商品图片
	public function upload()
	{
		$this->load->library('Upload');

		$config = array(
			'upload_path' => FCPATH.'assets/uploads/images/goods/'.date('Ym'),
			'allowed_types' => array('jpg', 'jpeg', 'gif', 'png'),
			'max_size' => 2048
		);
		
		if ( ! is_dir($config['upload_path']))
		{
			mkdir($config['upload_path'], 0777, TRUE);
		}
		
		$result = array();
		
		if ( ! $this->upload->config($config)->init())
		{
			$result = array(
				'code' => '1',
				'msg' => $this->upload->get_error()
			);
		}
		elseif ( ! $this->upload->do_upload('Filedata'))
		{
			$result = array(
				'code' => '2',
				'msg' => $this->upload->get_error()
			);
		}
		else
		{
			$this->load->library('Image');
			$this->image->init();
			
			$data = $this->upload->get_data();

			$new_image = str_replace('images/goods/', 'images/goods/160/', $data['absolute_filename']);

			$new_image_path = dirname($new_image);

			if ( ! is_dir($new_image_path))
			{
				mkdir($new_image_path, 0777, TRUE);
			}

			$this->image->thumb($data['absolute_filename'], $new_image, 160, 160, 85, TRUE);
			
			$result = array(
				'code' => 0,
				'msg' => str_replace('images/goods/', 'images/goods/160/', $data['relative_filename'])
			);
		}

		echo json_encode($result);
	}
	
	//商品搜索
	public function search()
	{
		$p = intval(get('p')) > 0 ? intval(get('p')) : 1;
		$per_page = 10;
	
		$type = in_array(intval(get('type')), array(1, 2, 3)) ? intval(get('type')) : 1; //搜索类型 1货号 2商品名称 3商品id
		$word = str_replace(array('_', '%'), array('\_', '\%'), addslashes(trim(get('word')))); //搜索词
		$category_id = intval(get('category_id')) > 0 ? intval(get('category_id')) : 0; //分类id
		$brand_id = intval(get('brand_id')) > 0 ? intval(get('brand_id')) : 0; //品牌id
		$supplier_id = intval(get('supplier_id')) > 0 ? intval(get('supplier_id')) : 0; //供应商id
		
		//计算总记录数
		$this->db->select('count(*) as count');
		$this->db->from('goods');
		$this->db->join('category', 'goods.category_id = category.id', 'left');
		$this->db->join('brand', 'goods.brand_id = brand.id', 'left');
		$this->db->join('supplier', 'goods.supplier_id = supplier.id', 'left');
		$this->db->join('specification', 'goods.id = specification.goods_id', 'left');
		if ($word)
		{
			switch ($type)
			{
				case 1:
					$this->db->where('goods.sku', $word);
					break;
				case 2:
					$this->db->like('goods.name', $word);
					break;
				case 3:
					$this->db->where('goods.id', $word);
					break;
			}
		}
		
		if ($category_id)
		{
			$this->db->where('category_id', $category_id);
		}
		
		if ($brand_id)
		{
			$this->db->where('brand_id', $brand_id);
		}
		
		if ($supplier_id)
		{
			$this->db->where('supplier_id', $supplier_id);
		}
		
		$query = $this->db->get();
		$result = $query->row_array();
		$count = intval($result['count']);
		
		//分页数据
		$this->db->select('goods.id, goods.name, goods.title, specification.cost_price, specification.market_price, specification.sale_price, brand.name as brand_name, supplier.name as supplier_name');
		$this->db->from('goods');
		$this->db->join('category', 'goods.category_id = category.id', 'left');
		$this->db->join('brand', 'goods.brand_id = brand.id', 'left');
		$this->db->join('supplier', 'goods.supplier_id = supplier.id', 'left');
		$this->db->join('specification', 'goods.id = specification.goods_id', 'left');
		
		if ($word)
		{
			switch ($type)
			{
				case 1:
					$this->db->where('goods.sku', $word);
					break;
				case 2:
					$this->db->like('goods.name', $word);
					break;
				case 3:
					$this->db->where('goods.id', $word);
					break;
			}
		}
		
		if ($category_id)
		{
			$this->db->where('category_id', $category_id);
		}
		
		if ($brand_id)
		{
			$this->db->where('brand_id', $brand_id);
		}
		
		if ($supplier_id)
		{
			$this->db->where('supplier_id', $supplier_id);
		}
		
		$this->db->limit($per_page, ($p - 1)*$per_page);
		$query = $this->db->get();
		$result = $query->result_array();
		$query->free_result();
		
		$this->load->library('page');
		$config = array(
			'current_page' => $p, 
			'total_rows' => $count,
			'per_page' => $per_page,
			'base_url' => admin_url('goods/search?'.http_build_query(get())),
			'page_mode' => 5
		);
		$this->page->config($config)->init();
		$page = $this->page->show('index');
		
		$json = array(
			'list' => $result,
			'page' => $page
		);
		
		echo json_encode($json);
	}
	
}